/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.widget;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-06-13 10:32<br/>
 *
 * <p>
 * 自定义旋转动画图形控件
 * </p>
 */
public class RotateImageView extends ImageView {
    private boolean isRotate = false;  // 是否正在旋转
    private ObjectAnimator mObjectAnimator;
    public static final boolean CLOCKWISE = false;
    public static final boolean ANTI_CLOCKWISE = true;

    public RotateImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public RotateImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RotateImageView(Context context) {
        this(context, null);
    }

    public boolean isRotate() {
        return isRotate;
    }

    /**
     * 构建旋转属性动画，并开始
     *
     * @param isReverse
     *         是否反转
     */
    public void start(boolean isReverse) {
        if (isRotate) {
            return;
        }
        clearAnimation();

        if (isReverse) {
            mObjectAnimator = ObjectAnimator.ofFloat(this, "rotation", 360f, 0f);
        } else {
            mObjectAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f);
        }
        mObjectAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mObjectAnimator.setRepeatMode(ValueAnimator.RESTART);
        mObjectAnimator.setInterpolator(new LinearInterpolator());
        mObjectAnimator.setDuration(700);
        mObjectAnimator.start();
        isRotate = true;
    }

    /**
     * 结束旋转动画
     */
    public void stop() {
        if (isRotate) {
            mObjectAnimator.end();
            isRotate = false;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        if (null != mObjectAnimator) {
            mObjectAnimator.end();
        }
        super.onDetachedFromWindow();
    }
}